#!/bin/bash
if [ $# -lt 2 ]; then 
  echo " Converts eps files (i.e. postscript files with "
  echo " %!PS-Adob-n.0 EPSF-n.n at the header followed by"
  echo " %%BoundingBox blah blah [can be (atend) or real values]"
  echo " ) to png format"
  echo " Usage: $0 <inputfile> <outputfile> [<device><resolution><border> <silent>]"
  echo " where device is the ghostscript device [png16m] "
  echo " resolution  is in dpi [100]"
  echo " border is the frame outside the image as a fraction of max(height,width) of image [0.05]"
exit 1
fi
 infile=$1; shift
 outfile=$1; shift
#now defaults
 res=100 #dpi
 device=png16m
 framefac=0.05

if [ $# -ge 3 ];then 
  res=$1
  device=$2
  framefac=$3
else
  echo 'using defaults..' 
fi
 
bbox=`gs -q -dNOPAUSE -dBATCH -sDEVICE=bbox $infile 2>&1 |\
                      grep '%%HiResBoundingBox:'|\
                          awk '{print $2,$3,$4,$5}'`
echo 'bounding box' $bbox 
#now  calculate the values needed by gs
factor=`echo $res | awk '{printf "%10.6f", $1/72}'`
scale=`echo $factor|awk '{printf "%10.6f", 1/$1}'`
framefactor=`echo dumb $bbox $framefac|awk \
    '{frame=($5-$3);f2=($5-$3);\
     if (f2>frame){frame=f2;} frame=int(frame*$6);\
     print frame}'`
#echo 'frame factor: '$framefactor 

size=`echo $factor $bbox $framefactor|awk \
     '{$2=$2-$6;$3=$3-$6;$4=$4+$6;$5=$5+$6;\
     sx=int(($4-$2)*$1); sy=int(($5-$3)*$1);\
     print sx "x" sy }'`
sizef=`echo $factor $bbox $framefactor|awk \
    '{ sx=int(($4-$2)*$1); sy=int(($5-$3)*$1);\
     print sx "x" sy }'`
echo 'size :' $size "( $sizef without frame )" 
#set -x
trans=`echo $bbox $framefactor|awk '{$1=$1-$5; $2=$2-$5; printf "%10.6f %10.6f", -$1, -$2}'`
gs  -q -dNOPAUSE -dBATCH -sDEVICE=$device -r$res -sOutputFile=$outfile \
    -g$size -c  $trans translate  -q $infile
#set +x
